#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"

#define MAXARGS 20
#define ARGLEN 100

char *makestring();
int execute(char *arglist[]);

int main() {
  char *arglist[MAXARGS + 1];
  char argbuf[ARGLEN];

  int numarg = 0;
  while (numarg < MAXARGS) {
    printf("Arg[%d]? ", numarg);
    if (fgets(argbuf, ARGLEN, stdin) && *argbuf != '\n') {
      arglist[numarg++] = makestring(argbuf);
    } else {
      if (numarg > 0) {
        arglist[numarg] = NULL;
        execute(arglist);
        perror("execvp");
        return 1;
      }
    }
  }

  return 0;
}

int execute(char *arglist[]) {
  execvp(arglist[0], arglist);
  perror("execvp failed");
  return 1;
}

char *makestring(char *buf) {
  char *cp;
  buf[strlen(buf) - 1] = '\0';
  cp = (char *)malloc(strlen(buf) + 1);
  if (cp == NULL) {
    fprintf(stderr, "no memory\n");
    exit(1);
  }
  strcpy(cp, buf);
  return cp;
}